import os

from flask import Flask

from config.config import *
from logging.config import dictConfig

dictConfig({
    "version": 1,
    "disable_existing_loggers": False,  # 不覆盖默认配置
    "formatters": {  # 日志输出样式
        "default": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",  # 控制台输出
            "level": "DEBUG",
            "formatter": "default",
        },
        "log_file": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "INFO",
            "formatter": "default",   # 日志输出样式对应formatters
            "filename": "./logs/flask.log",  # 指定log文件目录
            "maxBytes": 20*1024*1024,   # 文件最大20M
            "backupCount": 10,          # 最多10个文件
            "encoding": "utf8",         # 文件编码
        },

    },
    "root": {
        "level": "DEBUG",  # # handler中的level会覆盖掉这里的level
        "handlers": ["console", "log_file"],
    },
}
)

# 通过配置选择开发环境还是正式环境
def create_app():
    # create and configure the app
    app = Flask(__name__)

    app.config.from_object(BaseConfig)
    localEnv = str(app.config.get('LOCAL_ENV'))
    # 正式环境配置
    if localEnv == "pro":
        app.config.from_object(ProConfig)
    # 测试环境配置
    if localEnv == "dev":
        app.config.from_object(DevConfig)


    # 蓝图视图 类似spring注入
    from apps import MyError , Success
    from demo.restfull.RestfulDemo import RestfulDemobp
    app.register_blueprint(MyError.bp)
    app.register_blueprint(Success.bp)
    # restful整合蓝图
    app.register_blueprint(RestfulDemobp)
    return app